package com.nba.common.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.nba.common.dao.IJdbcDao;
import com.nba.common.service.IOtherService;
import com.nba.common.utils.CommonUtils;

@Service("otherService")
public class OtherServiceImpl implements IOtherService {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    private static BASE64Encoder encoder = new sun.misc.BASE64Encoder(); // 加码
    private static BASE64Decoder decoder = new sun.misc.BASE64Decoder(); // 解码


    @Autowired
    protected IJdbcDao jdbcDao;

    @Override
    public List<Map<String, Object>> createQrMapping(String url, List<Map<String, Object>> ids) throws Exception {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败

        for (Map<String, Object> id : ids) {
            String u = url + id.get("ID");
            // u=URLEncoder.encode(u,"utf-8");
            Map<String, Object> urlMap = new HashMap<String, Object>();
            BitMatrix matrix = new MultiFormatWriter().encode(u, BarcodeFormat.QR_CODE, 400, 400);
            BufferedImage bi = toBufferedImage(matrix);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();
            String base64code = encoder.encodeBuffer(bytes).trim();
            urlMap.put("base64code", base64code);
            urlMap.put("deviceName", id.get("DEVICE_NAME"));
            list.add(urlMap);
        }
        return list;
    }

    // 生成二维码
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }

    public static void main(String[] args) {
        String pwd = "123";
        String url = "http://localhost:7777/nba/login";
        // 获取签名
        Map<String, String> param = new HashMap<String, String>();
        param.put("app", "foodmall");
        param.put("time", "123456");
        param.put("usercode", "admin");
        param.put("passwd", "123456");
        String sign = CommonUtils.getSignByMD5(param, pwd);
        System.out.println("==============" + sign);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> m : param.entrySet()) {
            System.out.println("kkkk==="+m.getKey());
            if (m.getKey().equals("usercode")) {
                params.add(new BasicNameValuePair(m.getKey(), String.valueOf(m.getValue())));
            }
            if (m.getKey().equals("passwd")) {
                params.add(new BasicNameValuePair(m.getKey(), String.valueOf(m.getValue())));
            }
        }
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            HttpResponse response = client.execute(post);
            System.out.println("-----------------------------"+response);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 请求成功
                String entity = EntityUtils.toString(response.getEntity());
                System.out.println("entity==" + entity);
                JSONObject ooo = (JSONObject)JSONObject.parse(entity);
                //Map map = JsonUtils.getMap(entity);
                System.out.println("result=================" + ooo.get("result"));
               /* if ("1".equals(String.valueOf(map.get("result")))) {
                    String json = CommonUtils.decrypt(String.valueOf(map.get("rsObj")), pwd);
                    Map<String, Object> result = JsonUtils.getMap(json);
                    String userId = MapUtils.getString(result, "USER_ID");
                }*/
            }else{
                System.out.println("请求失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
